package com.nus;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

import com.nus.parsers.NdroidAPI;
import com.nus.parsers.ParserAPIs;
import com.nus.representations.IvleNews;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class IvleNewsActivity extends Activity {
	private ListView listview;
	public static ArrayList<IvleNews> news;
	public static String news_title;
	public static String news_description;
	public static String news_creationdate;
	public static String DateTime;
	public static String FinalDate;
	private String lv_arr[];
	public ImageButton home;
	private TextView title;
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		setContentView(R.layout.ivlenewslayout);
		 getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.window_title);
		 title = (TextView) findViewById(R.id.titleheader);
		 title.setText("News");
		listview = (ListView) findViewById(R.id.newsLV);
		 ImageView b = (ImageView)findViewById(R.id.home);
		  b.setImageDrawable(getResources().getDrawable(R.drawable.news));
		boolean netconn = checkInternetConnection();
		if (!netconn) {
			Toast.makeText(getApplicationContext(),
					"Please check your internet or 3G connection",
					Toast.LENGTH_LONG).show();
		}

		String url = "https://ivle.nus.edu.sg/api/Lapi.svc/PublicNews?APIKey=W7RtgW7GZKUpaEkJ1NwUD&TitleOnly=false&output=json";
		try {
			String response = getResponseText(url);

			Log.i("ResponseRohit", response);

			news = ParserAPIs.parseIvleNews(response);
			listview.setAdapter(new ListAdapter(IvleNewsActivity.this,
					R.id.rlt_main, news));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		OptionsActivity.pd.dismiss();

	}

	private class ListAdapter extends ArrayAdapter<IvleNews> {
		private ArrayList<IvleNews> mnews;
		private Context mContext;

		public ListAdapter(Context context, int textViewResourceId,
				ArrayList<IvleNews> list) { // --CloneChangeRequired
			super(context, textViewResourceId, list);
			this.mnews = list;
			this.mContext = context;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			View view = convertView;
			try {
				if (view == null) {
					LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
					view = vi.inflate(R.layout.list_item0, null);
				}
				final IvleNews listItem = mnews.get(position);

				if (listItem != null) {
					// setting list_item views
					TextView tv = (TextView) view.findViewById(R.id.name);
					tv.setText(listItem.getTitle());
					view.setClickable(true);
				
					view.setOnClickListener(new OnClickListener() {
						public void onClick(View arg0) {
						    //arg0.setBackgroundColor(Color.RED);
						   
							Intent myIntent = new Intent(IvleNewsActivity.this,
									IvleNews_Details_Activity.class);

							news_title = listItem.getTitle();
							news_description = listItem.getDescription();
							news_creationdate = NdroidAPI.formatDate(listItem
									.getCreatedDate());
							news_creationdate = news_creationdate.substring(0,
									10);

							startActivity(myIntent);
							arg0.setBackgroundColor(Color.parseColor("#191919"));
                           //finish();
						}
					});
					view.setOnTouchListener(new OnTouchListener() {
						
						public boolean onTouch(View v, MotionEvent event) {
							// TODO Auto-generated method stub
							v.setBackgroundColor(Color.BLUE);
							return false;
						}
					});
					
				}
			} catch (Exception e) {
				Log.i(IvleNewsActivity.ListAdapter.class.toString(),
						e.getMessage());
			}
			return view;
		}
	}

	public String getResponseText(String stringUrl) throws IOException {
		StringBuilder response = new StringBuilder();

		URL url = new URL(stringUrl);
		HttpURLConnection httpconn = (HttpURLConnection) url.openConnection();
		if (httpconn.getResponseCode() == HttpURLConnection.HTTP_OK) {
			BufferedReader input = new BufferedReader(new InputStreamReader(
					httpconn.getInputStream()), 8192);
			String strLine = null;
			while ((strLine = input.readLine()) != null) {
				response.append(strLine);
			}
			input.close();
		}
		return response.toString();
	}

	public boolean checkInternetConnection() {
		ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

		if (cm.getActiveNetworkInfo() != null
				&& cm.getActiveNetworkInfo().isAvailable()
				&& cm.getActiveNetworkInfo().isConnected()) {
			return true;

		} else {
			return false;
		}
	}
}
